<template>
  <div class="chat-container">
    <!-- 消息列表区域 -->
    <div class="messages-container" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index" class="message-item" :class="message.role">
        <div class="message-avatar">
          <img :src="message.role === 'user' ? userAvatar : aiAvatar" alt="avatar" />
        </div>
        <div class="message-content">
          <div class="message-text">
            <template v-if="message.role === 'assistant'">
              <!-- 思考内容 -->
              <div v-if="message.thought" class="thought-content">
                <div class="thought-header" @click="toggleThought(message)">
                  <el-icon :class="{ 'is-rotate': message.isThoughtExpanded }">
                    <ArrowRight />
                  </el-icon>
                  <span>思考过程</span>
                </div>
                <div v-show="message.isThoughtExpanded" class="thought-body">
                  <div v-html="formatThought(message.thought)"></div>
                </div>
              </div>
              <!-- 回答正文 -->
              <MarkdownRenderer :content="message.answer" />
            </template>
            <div v-else>{{ message.content }}</div>
            <!-- 加载状态指示器 -->
            <div v-if="loading && index == messages.length - 1"><el-icon class="loading"><Loading /></el-icon>思考中...</div>
          </div>
          <div class="message-time">{{ formatTime(message.timestamp) }}</div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-container">
      <div class="input-wrapper">
        <el-input v-model="userInput" type="textarea" :rows="3" resize="none" placeholder="请输入您的问题..."
          :disabled="loading" @keyup.enter.prevent="handleEnter" ref="inputArea" />
        <el-button class="send-button" type="primary" :disabled="loading || !userInput.trim()" @click="sendMessage">
          发送
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { Loading, ArrowRight } from '@element-plus/icons-vue'
import defaultUserAvatar from '@/assets/sidebar/czhi-default.svg'
import defaultAIAvatar from '@/assets/sidebar/fwenl-default.svg'
import { Message, MessageRole, MessageType, OpenAIAdapter } from './types'
import { OllamaAdapter } from './adapters/OllamaAdapter'
import { ModelConfig } from '@/utils/modelConfig'
import MarkdownRenderer from '@/components/MarkdownRenderer.vue'

// 定义props
const props = defineProps({
  systemPrompt: {
    type: String,
    default: ''
  }
})

// 状态定义
const userInput = ref('')
const messages = ref([])
const messagesContainer = ref(null)
const loading = ref(false)
const userAvatar = ref(defaultUserAvatar)
const aiAvatar = ref(defaultAIAvatar)
const inputArea = ref(null)

// 初始化AI模型适配器
const aiModel = ref(null)

// 初始化模型
const initModel = () => {
  const modelType = ModelConfig.getModelType()
  const config = {
    apiEndpoint: ModelConfig.getApiEndpoint(),
    modelName: ModelConfig.getModelName(),
    systemPrompt: props.systemPrompt
  }

  if (modelType === 'openai') {
    const apiKey = ModelConfig.getApiKey()
    if (!apiKey) {
      console.error('OpenAI模型需要配置API密钥')
      return false
    }
    config.apiKey = apiKey
    aiModel.value = new OpenAIAdapter(config)
  } else if (modelType === 'ollama') {
    if (!config.apiEndpoint || !config.modelName) {
      console.error('Ollama模型需要配置API端点和模型名称')
      return false
    }
    aiModel.value = new OllamaAdapter(config)
  }

  return true
}

// 处理消息发送
const sendMessage = async () => {
  if (!userInput.value.trim() || loading.value) return

  const userMessage = new Message({
    role: MessageRole.USER,
    type: MessageType.TEXT,
    content: userInput.value.trim()
  })

  messages.value.push(userMessage)
  userInput.value = ''
  loading.value = true
  await scrollToBottom()

  try {
    if (!aiModel.value) {
      throw new Error('AI模型未初始化')
    }

    // 创建一个临时的响应消息对象用于实时更新
    const tempMessage = {
      role: MessageRole.ASSISTANT,
      type: MessageType.TEXT,
      content: '',
      thought: null,
      answer: '',
      isThoughtExpanded: false,
      timestamp: Date.now()
    }
    messages.value.push(tempMessage)

    // 使用回调函数处理流式响应
    nextTick(() => {
      aiModel.value.sendMessage(userMessage, (response) => {
        const { thought, answer } = parseAIResponse(response.content)
        tempMessage.thought = thought
        tempMessage.answer = answer
        tempMessage.content = response.content
        
        loading.value = false
        console.info(response.content);
      })
    })
  } catch (error) {
    console.error('发送消息失败:', error)
    messages.value.push(
      new Message({
        role: MessageRole.SYSTEM,
        type: MessageType.TEXT,
        content: '抱歉，AI响应出现错误，请稍后重试'
      })
    )
    loading.value = false
  } finally {
    await scrollToBottom()
  }
}

// 解析AI响应
const parseAIResponse = (content) => {
  let thought = null
  let answer = content

  // 检查是否有思考过程
  const thinkMatch = content.match(/<think>([\s\S]*?)<\/think>/)
  if (thinkMatch) {
    thought = thinkMatch[1].trim()
    answer = content.replace(thinkMatch[0], '').trim()
  } else if (content.includes('<think/>')) {
    answer = content.replace('<think/>', '').trim()
  }

  return { thought, answer }
}

// 格式化思考内容
const formatThought = (thought) => {
  return thought.split('\n').map(line => line.trim()).filter(line => line).join('<br>')
}

// 切换思考内容的展开状态
const toggleThought = (message) => {
  message.isThoughtExpanded = !message.isThoughtExpanded
}

// Enter键发送消息
const handleEnter = (e) => {
  if (e.shiftKey) return
  sendMessage()
}

// 自动调整输入框高度
const autoResize = () => {
  const textarea = inputArea?.value?.$el.querySelector('textarea')
  if (!textarea) return
  textarea.style.height = 'auto'
  textarea.style.height = textarea.scrollHeight + 'px'
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString()
}

onMounted(() => {
  autoResize()
  initModel()
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f5f5f5;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  scrollbar-width: thin;
  scrollbar-color: #c0c4cc #f4f4f5;
}

.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f4f4f5;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 3px;
  transition: background-color 0.3s;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background-color: #909399;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.message-item.assistant {
  flex-direction: row;
}

.message-item.user {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  margin: 0 10px;
}

.message-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.message-content {
  max-width: 70%;
  background: white;
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-item.assistant .message-content {
  background: #e3f2fd;
}

.message-text {
  font-size: 14px;
  line-height: 1.5;
  word-break: break-word;
}

.thought-content {
  margin-bottom: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  overflow: hidden;
}

.thought-header {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: #eaecef;
  cursor: pointer;
  user-select: none;
}

.thought-header .el-icon {
  margin-right: 8px;
  transition: transform 0.3s;
}

.thought-header .el-icon.is-rotate {
  transform: rotate(90deg);
}

.thought-body {
  padding: 12px;
  white-space: pre-wrap;
}

.message-text :deep(p) {
  margin: 0.5em 0;
}

.message-text :deep(code) {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

.message-text :deep(pre) {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 1em;
  border-radius: 4px;
  overflow-x: auto;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.input-container {
  padding: 20px;
  background: white;
  border-top: 1px solid #eee;
}

.input-wrapper {
  display: flex;
  gap: 10px;
}

.input-wrapper :deep(.el-textarea) {
  flex: 1;
}

.input-wrapper :deep(.el-textarea__inner) {
  min-height: 40px;
  max-height: 150px;
  padding: 10px;
  font-size: 14px;
  line-height: 1.5;
}

.send-button {
  width: 80px;
}

.loading-message {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
}

.loading {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>
